//
//  WaterFlowLayout.swift
//  SwiftDemo
//
//  Created by lw on 2018/9/9.
//  Copyright © 2018年 mjsfax. All rights reserved.
//

import UIKit

protocol WaterFlowLayoutDataSource : class {
    func numberOfCols(_ waterFlow : WaterFlowLayout) -> Int
    func waterFlow(_ waterFlow : WaterFlowLayout, item : Int) -> CGFloat
}

class WaterFlowLayout: UICollectionViewFlowLayout {
    
    weak var dataSource : WaterFlowLayoutDataSource?
    fileprivate lazy var cellAttrs : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    fileprivate lazy var cols : Int = {
        return dataSource?.numberOfCols(self) ?? 2
    }()
    fileprivate lazy var totalHeights : [CGFloat] = Array(repeating: sectionInset.top, count: cols)
}

//准备布局 重写prepare
extension WaterFlowLayout {
    override func prepare() {
        super.prepare()
        
        // cell 对应--> UICollectionViewLayoutAttributes决定cell属性
        //1获取cell个数
        let itemCount = collectionView!.numberOfItems(inSection: 0)
        //2给每个cell创建一个UICollectionViewLayoutAttributes
        let itemsW = collectionView!.bounds.width - sectionInset.left - sectionInset.right - minimumLineSpacing * CGFloat(cols - 1)
        let itemW : CGFloat =  itemsW / CGFloat(cols)
        for i in 0..<itemCount {
            //1创建indexpath
            let indexPath = IndexPath(item: i, section: 0)
            //2根据indexpath创建对应的UICollectionViewLayoutAttributes
            let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            //3设置attr中的frame
            guard let itemH : CGFloat = dataSource?.waterFlow(self, item: i) else { //CGFloat(arc4random_uniform(150)) + 100
                fatalError("没有实现数据源方法：waterFlow")
            }
            let minH = totalHeights.min()!
            let minIndex = totalHeights.index(of: minH)!
            let itemX : CGFloat = sectionInset.left + (itemW + minimumLineSpacing) * CGFloat(minIndex)
            let itemY : CGFloat = minH + minimumLineSpacing
            attr.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
            //4保存attr
            cellAttrs.append(attr)
            //5保存当前高度
            totalHeights[minIndex] = minH + minimumLineSpacing + itemH
        }
        
    }
}

//返回准备好所有布局
extension WaterFlowLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cellAttrs
    }
}

//设置contentSize
extension WaterFlowLayout {
    override var collectionViewContentSize: CGSize {
        return CGSize(width: 0, height: totalHeights.max()!)
    }
}
